<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2021/01/15
 * Time: 11:31
 * @link http://www.lmterp.cn
 */

namespace app\common\model;

class FinanceInvoiceSetting extends BaseModel
{
    protected $pk = 'invoice_id';

    /**
     * 增值税发票
     * @var int
     */
    const INVOICE_TYPE_TAX = 0;

    /**
     * 普通发票
     * @var int
     */
    const INVOICE_TYPE_GENERAL = 10;

    public static $INVOICE_TYPE = [
        self::INVOICE_TYPE_TAX     => '增值税发票',
        self::INVOICE_TYPE_GENERAL => '普通发票',
    ];

    protected function getTypeAttr($value)
    {
        return isset(self::$INVOICE_TYPE[$value]) ? self::$INVOICE_TYPE[$value] : $value;
    }

    /**
     * 获取默认发票配置
     * @return FinanceInvoiceSetting
     * @date 2021/01/15
     * @author longli
     */
    public static function getDefaultInvoice()
    {
        return static::where([
            'is_default' => static::IS_YES,
            'status' => static::IS_YES
        ])->find();
    }

    /**
     * 设置默认发票
     * @param int|self $invoice 发票id，发票
     * @param bool $force 强制设置
     * @return bool
     * @date 2021/01/15
     * @author longli
     */
    public static function setDefault($invoice, $force = false)
    {
        $invoice = self::getObj($invoice);
        if(empty($invoice)) return false;
        if(!$force && $invoice->is_default == self::IS_YES) return true;
        static::where("invoice_id", ">", 0)
            ->update(['is_default' => self::IS_NO]);
        static::where("invoice_id", $invoice->invoice_id)->update(['is_default' => self::IS_YES]);
        return true;
    }

    /**
     * 获取所有发票配置
     * @return static[]
     * @date 2021/01/15
     * @author longli
     */
    public static function getAll()
    {
        return static::where([
            'status' => static::IS_YES
        ])->order("is_default desc, sort desc")
        ->select();
    }
}
